//
//  TwitterClient.m
//  TwitterFon
//
//  Created by kaz on 7/13/08.
//  Copyright naan studio 2008. All rights reserved.
//

#import "TwitPicClient.h"
#import "StringUtil.h"
#import "REString.h"
#import "URLStore.h"
#import "GuaziAppDelegate.h"

@interface NSObject (TwitterClientDelegate)
- (void)twitPicClientDidPost:(TwitPicClient*)sender mediaId:(NSString*)mediaId;
- (void)twitPicClientDidFail:(TwitPicClient*)sender error:(NSString*)error detail:(NSString*)detail;
- (void)twitPicClientDidDone:(TwitPicClient*)sender content:(NSString*)content;
@end

@implementation TwitPicClient

- (id)initWithTarget:(id)aDelegate
{
    [super initWithDelegate:aDelegate];
    return self;
}

+ (NSString*) nameValString: (NSDictionary*) dict {
	NSArray* keys = [dict allKeys];
	NSString* result = [NSString string];
	int i;
	for (i = 0; i < [keys count]; i++) {
        result = [result stringByAppendingString:
                  [@"--" stringByAppendingString:
                   [TWITTERFON_FORM_BOUNDARY stringByAppendingString:
                    [@"\r\nContent-Disposition: form-data; name=\"" stringByAppendingString:
                     [[keys objectAtIndex: i] stringByAppendingString:
                      [@"\"\r\n\r\n" stringByAppendingString:
                       [[dict valueForKey: [keys objectAtIndex: i]] stringByAppendingString: @"\r\n"]]]]]]];
	}

	return result;
}


/*
+ (NSString*) uploadTweetImage:(UIImage*)image
{
    NSString* url = [[URLStore sharedInstance] urlForKey:kAPIMethodTweetUpload format:@"json"];
    
    NSMutableData *data = [NSMutableData data];

    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:kOAuthConsumerKey, @"source", nil];
    NSString* param = [TwitPicClient nameValString:dic];
    
    param = [param stringByAppendingString:[NSString stringWithFormat:@"--%@\r\n", TWITTERFON_FORM_BOUNDARY]];
    param = [param stringByAppendingString:@"Content-Disposition: form-data; name=\"pic\";filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"];
    
    [data appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSData* jpeg = UIImageJPEGRepresentation( image, 0.8 );
    NSLog(@"jpeg size: %d", [jpeg length]);
    [data appendData:jpeg];
    
    NSString *footer = [NSString stringWithFormat:@"\r\n--%@--\r\n", TWITTERFON_FORM_BOUNDARY];
    [data appendData:[footer dataUsingEncoding:NSUTF8StringEncoding]];
    
    
	NSHTTPURLResponse* response;
	NSError* error = nil;
    id result = [TFConnection sendSynchronousRequest:url method:@"POST" body:data
                                response:&response error:&error];
    NSLog(@"code=%d", response.statusCode);
    if ( response.statusCode == 200 ) {
        [GuaziAppDelegate showAlert:@"成功上传图片"]; 
        return @"";
    }
    else {
        [GuaziAppDelegate showAlert:@"上传图片失败"]; 
        
        NSString* msg = [NSString stringWithFormat:@"Error: %@ %@",
                         [error localizedDescription],
                         [[error userInfo] objectForKey:NSErrorFailingURLStringKey]];
        
        NSLog(@"Connection failed: %@", msg);
        return nil;
    }
}
*/
 
- (void)upload:(UIImage*)image status:(NSString *)status
{
	//NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
	//NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"password"];

	needAuth = YES;
	//NSString* url = [NSString stringWithFormat:@"http://api.t.sina.com.cn/statuses/upload.json"];
    NSString* url = [[URLStore sharedInstance] urlForKey:kAPIMethodTweetUpload format:@"json"];
    
    NSData *jpeg = UIImageJPEGRepresentation(image, 0.8);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                         //username, @"username",
                         //password, @"password",
						 //@"3983859935", @"source",
						 status, @"status",
                         nil];
    
    NSString *param = [TwitPicClient nameValString:dic];
    NSString *footer = [NSString stringWithFormat:@"\r\n--%@--\r\n", TWITTERFON_FORM_BOUNDARY];
    
    param = [param stringByAppendingString:[NSString stringWithFormat:@"--%@\r\n", TWITTERFON_FORM_BOUNDARY]];
    param = [param stringByAppendingString:@"Content-Disposition: form-data; name=\"pic\";filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"];
    NSLog(@"jpeg size: %d", [jpeg length]);

    NSMutableData *data = [NSMutableData data];
    [data appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:jpeg];
    [data appendData:[footer dataUsingEncoding:NSUTF8StringEncoding]];

    [self post:url data:data];
    
}

- (void)TFConnectionDidFailWithError:(NSError*)error
{
    [delegate twitPicClientDidFail:self error:@"Connection Failed" detail:[error localizedDescription]];
}

- (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    [delegate twitPicClientDidFail:self error:@"Authentication Failed" detail:@"Wrong username/Email and password combination."];
}

- (void)TFConnectionDidFinishLoading:(NSString*)content
{
    NSLog(@"%@", content);
    
    if (statusCode != 200) {
        NSString *error = [NSString stringWithFormat:@"TwitPic Error: %d", statusCode];
        [delegate twitPicClientDidFail:self error:error detail:@"Failed to upload photo to TwitPic."];
        return;
    }
    else {
        [delegate twitPicClientDidDone:self content:content];
    }

	/*
    NSMutableArray *substr = [NSMutableArray array];
    NSRange r;
    
    r = [content  rangeOfString:@"<rsp stat=\"ok\">"];
    if (r.location != NSNotFound) {
        if ([content matches:@"<mediaid>([A-Za-z0-9]+)</mediaid>" withSubstring:substr]) {
            NSLog(@"mediaid = %@", [substr objectAtIndex:0]);
            [delegate twitPicClientDidPost:self mediaId:[substr objectAtIndex:0]];
        }
        else {
            [delegate twitPicClientDidFail:self error:@"TwitPic Error" detail:@"TwitPic responded unknown content."];
        }
    }
    else if ([content matches:@"<err +code=\"([0-9]+)\" +msg=\"([A-Za-z0-9\\. ]+)\" />" withSubstring:substr]) {
        NSLog(@"TwitPic error: %@ %@", [substr objectAtIndex:0], [substr objectAtIndex:1]);
        [delegate twitPicClientDidFail:self error:[NSString stringWithFormat:@"TwitPic Error: %@", [substr objectAtIndex:0]]
                                                                      detail:[substr objectAtIndex:1]];
    }
    else {
        [delegate twitPicClientDidFail:self error:@"TwitPic Error" detail:@"TwitPic responded unknown content."];
    }
	*/
}


@end
